package com.test45_JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Condition实现线程同步
 */
public class Demo09_Condition {
    public static String msg = null;

    public static void main(String[] args) throws Exception {
        Lock lock = new ReentrantLock();    // 获取一个互斥锁
        Condition condition = lock.newCondition();  // 获取Condition接口实例
        lock.lock();    // 锁定主线程
        try {
            new Thread(() -> {  // 创建子线程，修改msg的属性内容
                lock.lock();    // 锁定子线程
                System.out.printf("【%s】准备进行数据的处理操作%n", Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(2);
                    msg = "沐言科技：www.yootk.com/resources";   // 修改数据内容
                    condition.signal();  // 唤醒第一个等待的线程
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }, "子线程").start();
            condition.await();  // 主线程等待
            System.out.println("【主线程】得到最终处理的结果：" + msg);
        } finally {
            lock.unlock();
        }
    }
}
